<?php
namespace App\Service;


use App\Entity\Shop;
use App\Entity\ShopTag;
use App\Repository\ConfigRepository;
use App\Repository\ShopTagRepository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class ShopService extends ServiceEntityRepository
{
    const __TAG_PERSON__        = 1;
    const __TAG_COMPANY__       = 2;
    const __TAG_INSURE__        = 3;
    const __TAG_GOLD__          = 4;

    public $shopTagRepository;
    public $configRepository;

    public function __construct(
        ManagerRegistry $registry
        ,ShopTagRepository $shopTagRepository
        ,ConfigRepository $configRepository
    )
    {
        parent::__construct($registry, Shop::class);
        $this->shopTagRepository = $shopTagRepository;
        $this->configRepository = $configRepository;
    }

    public function hasTag(Shop $shop,int $tagId)
    {
        $tag = $this->shopTagRepository->find($tagId);
        if ($shop->getTags()->contains($tag)) {
            return true;
        }else{
            return false;
        }
    }


    /**
     * @param Shop $shop
     * @param int $tagId
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addTagId(Shop $shop,int $tagId)
    {
        $tag = $this->shopTagRepository->find($tagId);
        $shop->addTag($tag);
        $this->_em->persist($shop);
        $this->_em->flush();
    }


    public function getCategoryLimit(Shop $shop)
    {
//取出设置中默认的可选栏目数量，
        $def = $this->configRepository->getByK("NUM_SHOP_CAT_DEFAULT");
        $numCat1 = myExplodeNumbers($def)[0]??0;
        $numCat2 = myExplodeNumbers($def)[1]??0;

        //检查用户是否是保证金商家
        if ($this->hasTag($shop,ShopService::__TAG_INSURE__)) {
            //有保证金的标签
            $insure = $this->configRepository->getByK("NUM_SHOP_CAT_INSURE");
            $numCat1 += myExplodeNumbers($insure)[0]??0;
            $numCat2 += myExplodeNumbers($insure)[1]??0;
        }
        $data["cat1Max"] = $numCat1;
        $data["cat2Max"] = $numCat2;

        //当前数量
        $data["cat1Cur"] = 0;
        $data["cat2Cur"] = 0;
        $cats = $shop->getCategories();
        $data["cat1"] = [];
        $data["cat1En"] = [];
        $data["cat2"] = [];
        $data["cat2En"] = [];
        foreach ($cats as $cat) {
            if ($cat->getParent() == null) {
                //是一级分类
                $data["cat1Cur"] += 1;
                $data["cat1"][] = $cat->getId();
                $data["cat1En"][] = $cat;
            }else{
                //二级分类
                $data["cat2Cur"] += 1;
                $data["cat2"][] = $cat->getId();
                $data["cat2En"][] = $cat;
            }
        }
        return $data;
    }
}